<?php

namespace App\Http\Controllers;

use App\Http\Requests\LoginRequest;
use App\Http\Requests\RegisterRequest;
use App\Http\Requests\SetPasswordRequest;
use App\Model\User;
use App\Traits\Password;
use GuzzleHttp\Client;
use Hash;
use Hashids\Hashids;

class AuthController extends Controller
{
    use Password;

    /**
     * 注册
     *
     * @param RegisterRequest $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function register(RegisterRequest $request)
    {
//        if (! $this->smsChecker($request)) {
//            return response()->json([
//                'errors' => [
//                    ['key' => 'sms_code', 'value' => '手机验证码错误'],
//                ],
//            ], 422);
//        }

        $user = new User();
        // 判断是否填入邀请码
        if ($request->has('invite_code')) {// 有邀请人
            $hashids     = new Hashids(
                config('services.hashids.salt'),
                config('services.hashids.minHashLength'),
                config('services.hashids.alphabet')
            );
            $invite_code = $hashids->decode($request->input('invite_code'));
            if (empty($invite_code)) {
                return response()->json(['error' => '邀请码错误'], 404);
            }
            $user->pid = $invite_code[0];
        } else {
            $user->pid = 0;
        }
        $user->mobile   = $request->input('mobile');
        $user->password = bcrypt($request->input('password'));
        if (! $user->save()) {
            return response()->json(['error' => '网络异常，请重试'], 500);
        }

        return response()->json(['message' => '注册成功'], 200);
    }

    /**
     * 登录
     *
     * @param LoginRequest $request
     * @return mixed
     */
    public function login(LoginRequest $request)
    {
        $http     = new Client;
        $response = $http->post($request->root() . '/oauth/token', [
            'form_params' => [
                'grant_type'    => 'password',
                'client_id'     => '5',
                'client_secret' => 'oHvqe0BQVySwuqsawKJlsSf7ih9T48jJncjioN6R',
                'username'      => $request->input('mobile'),
                'password'      => $request->input('password'),
                'scope'         => '*',
            ],
        ]);

        return json_decode((string)$response->getBody(), true);
    }

    public function passwordReset(SetPasswordRequest $request)
    {
        $user = User::where('mobile', $request->input('mobile'))->first();

        // 判断交易密码登录密码是否一致User
        $password = $request->input('password');
        if (Hash::check($password, $user->pay_password)) {
            return response()->json(['error' => '交易密码不可与登录密码一致！'], 403);
        }

        $user->password = bcrypt($password);
        if (! $user->save()) {
            return response()->json(['error' => '网络异常，请重试'], 500);
        }

        return response()->json(['message' => '密码重置成功'], 200);
    }

}